package com.hanzhong.travel.service.impl;

import com.hanzhong.travel.entity.Message;
import com.hanzhong.travel.mapper.MessageMapper;
import com.hanzhong.travel.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息服务实现类
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public boolean addMessage(Message message) {
        return messageMapper.insert(message) > 0;
    }

    @Override
    public Message getMessageById(Long id) {
        return messageMapper.selectById(id);
    }

    @Override
    public List<Message> getAllMessages() {
        return messageMapper.selectAll();
    }

    @Override
    public Map<String, Object> getMessagesByPage(int page, int size) {
        // 计算分页偏移量
        int offset = (page - 1) * size;
        
        // 查询分页数据
        List<Message> messages = messageMapper.selectByPage(offset, size);
        
        // 查询总数
        int total = messageMapper.selectCount();
        
        // 计算总页数
        int totalPages = (int) Math.ceil((double) total / size);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("content", messages);
        result.put("totalElements", total);
        result.put("totalPages", totalPages);
        result.put("size", size);
        result.put("number", page);
        result.put("hasNext", page < totalPages);
        result.put("hasPrevious", page > 1);
        
        return result;
    }

    @Override
    public boolean markAsRead(Long id) {
        return messageMapper.updateReadStatus(id, 1) > 0;
    }

    @Override
    public boolean deleteMessage(Long id) {
        return messageMapper.deleteById(id) > 0;
    }
} 